package com.jason.unpluggedsuperstar.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.Time;
import android.util.Log;

import com.android.dataframework.DataFramework;
import com.android.dataframework.Entity;

public class VideoUtils {
	
	public static final String VIDEO_TABLE = "video_list";
	public static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;

	public static final String COL_ID = "_id";
	public static final String COL_TITLE = "title";
	public static final String COL_DESCRIPTION = "description";
	public static final String COL_DURATION = "video_duration";
	public static final String COL_LOCATION = "video_location";
	public static final String COL_REAL_LOCATION = "video_real_location";
	public static final String COL_STATUS = "status";
	public static final String COL_CREATED_DT = "created_datetime";
	public static final String COL_UPLOADED_DT = "uploaded_datetime";
	
	public static final String VID_STATUS_CREATED = "created";
	public static final String VID_STATUS_UPLOADED = "uploaded";
	
	
	private Activity mActivity;
	private Uri fileUri;
	
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	
	public VideoUtils(Activity activity){
		mActivity = activity;
	}
	
	public void startRecord(){
		//create new Intent
	    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

	    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);  // create a file to save the video
	    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high

	    // start the Video Capture Intent
	    mActivity.startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
	}

	/** Create a file Uri for saving an image or video */
	private static Uri getOutputMediaFileUri(int type){
	      return Uri.fromFile(getOutputMediaFile(type));
	}

	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(int type){
	    // To be safe, you should check that the SDCard is mounted
	    // using Environment.getExternalStorageState() before doing this.

	    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "UnpluggedSuperStar");
	    // This location works best if you want the created images to be shared
	    // between applications and persist after your app has been uninstalled.

	    // Create the storage directory if it does not exist
	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.d("MyCameraApp", "failed to create directory");
	            return null;
	        }
	    }

	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    File mediaFile;
	    if (type == MEDIA_TYPE_IMAGE){
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "IMG_"+ timeStamp + ".jpg");
	    } else if(type == MEDIA_TYPE_VIDEO) {
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "VID_"+ timeStamp + ".mp4");
	    } else {
	        return null;
	    }

	    return mediaFile;
	}
	
	public static boolean hasImageCaptureBug() {

	    // list of known devices that have the bug
	    ArrayList<String> devices = new ArrayList<String>();
	    devices.add("android-devphone1/dream_devphone/dream");
	    devices.add("generic/sdk/generic");
	    devices.add("vodafone/vfpioneer/sapphire");
	    devices.add("tmobile/kila/dream");
	    devices.add("verizon/voles/sholes");
	    devices.add("google_ion/google_ion/sapphire");

	    return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
	            + android.os.Build.DEVICE);

	}
	
	public static boolean createVideoEntry(Context context , String title , String description , String videoUri){
		try {
			DataFramework.getInstance().open(context, "com.jason.unpluggedsuperstar");
			
			Entity entity = new Entity(VIDEO_TABLE);
			
			entity.setValue(VideoUtils.COL_TITLE,title);
			entity.setValue(VideoUtils.COL_DESCRIPTION, description);
			entity.setValue(VideoUtils.COL_REAL_LOCATION, videoUri);
			entity.setValue(VideoUtils.COL_STATUS, VID_STATUS_CREATED);
			
			//get video length
			Uri uri = Uri.parse(videoUri);
			Cursor cursor = MediaStore.Video.query(context.getContentResolver(), uri, new String[]{MediaStore.Video.VideoColumns.DURATION,MediaStore.Video.VideoColumns.DATA,MediaStore.Video.VideoColumns.DATE_ADDED});
			
			if(cursor.moveToFirst()) {
			    String duration = cursor.getString(0);
			    entity.setValue(VideoUtils.COL_DURATION, duration);
			    
			    String location = cursor.getString(1);
			    entity.setValue(VideoUtils.COL_LOCATION, location);
			    
			    String date_added = cursor.getString(2);
			    entity.setValue(VideoUtils.COL_CREATED_DT, date_added);
			}
			cursor.close();
			
			DataFramework.getInstance().close();
			return entity.save();
			
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean updateVideoEntry(Context context,String id){
		try {
			DataFramework.getInstance().open(context, "com.jason.unpluggedsuperstar");
			Entity entity = DataFramework.getInstance().getEntityList(VIDEO_TABLE, COL_ID+"="+id).get(0);
			
			entity.setValue(COL_STATUS, VID_STATUS_UPLOADED);
			entity.setValue(COL_UPLOADED_DT, String.valueOf(System.currentTimeMillis()));
			
			return entity.save();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}
